/*
 *
 *  Copyright (C) 2012-2024
 *  All rights reserved, Designed By 杭州连线客信息技术有限公司
 *  注意：
 *  本软件为杭州连线客信息技术有限公司开发研制，未经购买不得使用
 *  购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
 *  一经发现盗用、分享等行为，将追究法律责任，后果自负
 *
 */

package com.lxk.finance.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lxk.finance.domain.AccUserAccount;
import com.lxk.finance.domain.FinanceDictConstant;
import com.lxk.finance.domain.bo.AccUserAccountBo;
import com.lxk.finance.domain.bo.AccUserAccountRecordBo;
import com.lxk.finance.domain.vo.AccUserAccountVo;
import com.lxk.finance.mapper.AccUserAccountMapper;
import com.lxk.finance.service.IAccUserAccountRecordService;
import com.lxk.finance.service.IAccUserAccountService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.constant.Constants;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.system.domain.vo.SysDictDataVo;
import org.dromara.system.service.ISysDictTypeService;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 用户账户Service业务层处理
 *
 * @author LXK-RY5
 * @date 2024-07-08
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class AccUserAccountServiceImpl implements IAccUserAccountService {

    private final AccUserAccountMapper baseMapper;
    private final ISysDictTypeService dictTypeService;
    private final IAccUserAccountRecordService accUserAccountRecordService;


    @Override
    public Optional<AccUserAccountVo> findByUserIdAndAccountType(Long userId, AccUserAccountBo.AccountType accountType) {
        AccUserAccountVo accUserAccountVo = baseMapper.selectVoOne(Wrappers.<AccUserAccount>lambdaQuery()
            .eq(AccUserAccount::getUserId, userId)
            .eq(AccUserAccount::getAccountType, accountType.getCode()));
        return Optional.ofNullable(accUserAccountVo);
    }

    @Override
    public AccUserAccountVo findByUserIdAndAccountType(Long userId, Integer accountType) {
        return baseMapper.selectVoOne(Wrappers.<AccUserAccount>lambdaQuery()
            .eq(AccUserAccount::getUserId, userId)
            .eq(AccUserAccount::getAccountType, accountType));
    }

    @Override
    public Boolean reduceAccount(Long userId,
                                 String userType,
                                 String orderSn,
                                 BigDecimal amount,
                                 AccUserAccountBo.AccountType accountType,
                                 String extraInfo) {
        log.info("reduceAccount userId：{}, amount：{}，accountType：{}, extraInfo:{},orderSn:{}", userId, amount, accountType, extraInfo, orderSn);
        Assert.notNull(userId);
        Assert.notNull(accountType);
        AccUserAccountVo accUserAccountVo = findByUserId(userId, accountType, userType);
        Assert.notNull(accUserAccountVo, "账户未找到");
        Long id = accUserAccountVo.getId();
        int update = baseMapper.update(null, Wrappers.<AccUserAccount>lambdaUpdate()
            .setSql("amount = amount - " + amount)
            .eq(AccUserAccount::getId, id)
            .last(StrUtil.format("and (amount -  {}) >= 0", amount)));
        if (update == 1) {
            accUserAccountRecordService.addRecord(orderSn, amount.multiply(new BigDecimal("-1")), extraInfo, AccUserAccountRecordBo.IncomeStatus.OUT, accUserAccountVo);
        }
        return update == 1;
    }


    @Override
    public Boolean addAccount(Long userId,
                              String userType,
                              String orderSn,
                              BigDecimal amount,
                              AccUserAccountBo.AccountType accountType,
                              String extraInfo
    ) {
        log.info("addAccount userId：{}, amount：{}，accountType：{}, extraInfo:{},orderSn:{}", userId, amount, accountType, extraInfo, orderSn);
        Assert.notNull(userId);
        Assert.notNull(accountType);
        AccUserAccountVo accUserAccountVo = findByUserId(userId, accountType, userType);
        Assert.notNull(accUserAccountVo, "账户未找到");
        Long id = accUserAccountVo.getId();
        int update = baseMapper.update(null, Wrappers.<AccUserAccount>lambdaUpdate()
            .setSql("amount = amount + " + amount)
            .eq(AccUserAccount::getId, id));
        if (update == 1) {
            accUserAccountRecordService.addRecord(orderSn, amount, extraInfo, AccUserAccountRecordBo.IncomeStatus.IN, accUserAccountVo);
        }
        return update == 1;
    }

    @Override
    public void registerAccount(Long userId, String userType) {
        List<SysDictDataVo> sysDictDataVos = dictTypeService.selectDictDataByType(FinanceDictConstant.ACCOUNT_TYPE);
        sysDictDataVos.stream().forEach(item -> {
            String dictValue = item.getDictValue();
            AccUserAccountBo add = new AccUserAccountBo();
            add.setAccountType(Integer.valueOf(dictValue));
            add.setUserId(userId);
            add.setUserType(userType);
            add.setAmount(BigDecimal.ZERO);
            add.setStatus(Integer.valueOf(Constants.SUCCESS));
            this.insertByBo(add);
        });
    }

    /**
     * 查询IdList用户账户Map
     */
    @Override
    public Map<Long, AccUserAccountVo> queryMapByIdList(List<Long> idList) {
        return this.queryByIdList(idList).stream().collect(Collectors.toMap(AccUserAccountVo::getId, v -> v));
    }

    /**
     * 查询用户账户Map
     */
    @Override
    public Map<Long, AccUserAccountVo> queryMap(AccUserAccountBo bo) {
        return this.queryList(bo).stream().collect(Collectors.toMap(AccUserAccountVo::getId, v -> v));
    }

    /**
     * 查询用户账户IdList
     */
    @Override
    public List<AccUserAccountVo> queryByIdList(List<Long> idList) {
        if (CollUtil.isEmpty(idList)) {
            return CollUtil.newArrayList();
        }
        LambdaQueryWrapper<AccUserAccount> lqw = Wrappers.lambdaQuery();
        lqw.in(AccUserAccount::getId, idList);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 查询用户账户
     *
     * @param id 主键
     * @return 用户账户
     */
    @Override
    public AccUserAccountVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询用户账户列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 用户账户分页列表
     */
    @Override
    public TableDataInfo<AccUserAccountVo> queryPageList(AccUserAccountBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<AccUserAccount> lqw = buildQueryWrapper(bo);
        Page<AccUserAccountVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的用户账户列表
     *
     * @param bo 查询条件
     * @return 用户账户列表
     */
    @Override
    public List<AccUserAccountVo> queryList(AccUserAccountBo bo) {
        LambdaQueryWrapper<AccUserAccount> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<AccUserAccount> buildQueryWrapper(AccUserAccountBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<AccUserAccount> lqw = Wrappers.lambdaQuery();
        lqw.orderByDesc(AccUserAccount::getId);
        lqw.eq(bo.getUserId() != null, AccUserAccount::getUserId, bo.getUserId());
        lqw.eq(bo.getStatus() != null, AccUserAccount::getStatus, bo.getStatus());
        lqw.eq(bo.getAccountType() != null, AccUserAccount::getAccountType, bo.getAccountType());
        lqw.eq(bo.getAmount() != null, AccUserAccount::getAmount, bo.getAmount());
        lqw.between(params.get("beginCreateTime") != null && params.get("endCreateTime") != null,
            AccUserAccount::getCreateTime, params.get("beginCreateTime"), params.get("endCreateTime"));
        lqw.between(params.get("beginUpdateTime") != null && params.get("endUpdateTime") != null,
            AccUserAccount::getUpdateTime, params.get("beginUpdateTime"), params.get("endUpdateTime"));
        lqw.eq(StringUtils.isNotBlank(bo.getUserType()), AccUserAccount::getUserType, bo.getUserType());
        return lqw;
    }

    /**
     * 新增用户账户
     *
     * @param bo 用户账户
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(AccUserAccountBo bo) {
        AccUserAccount add = MapstructUtils.convert(bo, AccUserAccount.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改用户账户
     *
     * @param bo 用户账户
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(AccUserAccountBo bo) {
        AccUserAccount update = MapstructUtils.convert(bo, AccUserAccount.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(AccUserAccount entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除用户账户信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    private AccUserAccountVo findByUserId(Long userId, AccUserAccountBo.AccountType accountType, String userType) {
        AccUserAccountVo accUserAccountVo = baseMapper.selectVoOne(Wrappers.<AccUserAccount>lambdaQuery()
            .eq(AccUserAccount::getUserType, userType)
            .eq(AccUserAccount::getUserId, userId)
            .eq(AccUserAccount::getAccountType, accountType.getCode()));
        return accUserAccountVo;
    }
}
